package br.unisc.robokit.connection;

import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import br.unisc.robokit.utils.Utils;
import br.unisc.robokit.webcam.InfoComp;

public class Conexao {
	private static Socket sock;
	private InfoComp info;

	public Conexao(InfoComp info) throws UnknownHostException, IOException {
		this.info = info;

		new Thread() {
			@Override
			public void run() {
				try {
					String line = Utils.readLine();
					try {
						String[] parts = line.split(":");
						String host = parts[0];
						int port = Integer.valueOf(parts[1]);
						sock = new Socket(host, port);
						System.out
								.println("Conectando em " + host + ":" + port);
					} catch (Exception e) {
						e.printStackTrace();
					}

					if (sock == null) {
						sock = new Socket("robokit.unisc.br", 80);
						System.out.println("Conectando em robokit.unisc.br:80");
					}
					Thread receive = new Thread() {
						@Override
						public void run() {
							try {
								while (true) {
									if (sock.getInputStream().available() > 0) {
										int i = sock.getInputStream().read();
										recebe(i);
									} else {
										Thread.sleep(100);
									}
								}
							} catch (Exception e) {
								e.printStackTrace();
							}
						}
					};

					receive.start();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();

	}

	public static boolean getBit(int value, int bit) {
		value = value >> bit;
		value = value & 0x01;
		return value == 0 ? false : true;
	}

	public void recebe(int i) {
		info.setLed1(getBit(i, 0));
		info.setLed2(getBit(i, 1));
		info.setLed3(getBit(i, 2));
		info.setLed4(getBit(i, 3));
		info.setMC1(getBit(i, 4));
		info.setMC2(getBit(i, 5));
		info.setMP(getBit(i, 6));
	}

	public static void envia(String comando) {
		if (sock != null && sock.isConnected()) {
			comando = comando + "\n";
			try {
				sock.getOutputStream().write(comando.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
